/**
 * 
 */
package org.pump.client.type;

import java.util.Arrays;

import org.pump.client.codec.WriteRowEvent;
import org.pump.client.util.TypeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author liudong03
 *
 */
public class MysqlDecimal {
	private static final Logger mylog = LoggerFactory
			.getLogger(MysqlDecimal.class);
	public static final int E_DEC_OK = 0;
	public static final int E_DEC_ERROR = 31;
	public static final int E_DEC_BAD_NUM = 8;
	public static final int E_DEC_DIV_ZERO = 4;
	public static final int E_DEC_FATL_ERROR = 30;
	public static final int E_DEC_OOM = 16;
	public static final int E_DEC_OVERFLOW = 2;
	public static final int E_DEC_TRUNCATED = 1;
	public static final int DEC_SIZE = 9;
	public static int dig2bytes[] = {0,1,1,2,2,3,3,4,4,4};
	byte[] data;
	StringBuilder sb;
	int percision;
	int scale;
	/**
	 * 
	 */
	public MysqlDecimal(byte[] data,int percision,int scale) {
		// TODO Auto-generated constructor stub
		this.data = data;
		this.sb = new StringBuilder();
		this.percision = percision;
		this.scale = scale;
		this.format();
		
	}
	
	public byte[] getData()
	{
		return this.data;
	}
	
	public boolean format()
	{
		int intg = percision - scale;
		int intg0 = intg / 9,frac0 = scale / 9;
		int intg0x = intg - intg0 * 9,frac0x = scale - frac0*9;
		
		int mask = ((this.data[0] & 0x80) != 0)?0:-1;
		
		this.data[0] = (byte) (this.data[0] ^ 0x80);
		
		boolean sign = (mask != 0?true:false);
		if(sign) this.sb.append("-");
		
		int curbyte = 0;
		
		if(intg0x > 0)
		{
			int i = MysqlDecimal.dig2bytes[intg0x];
			int x = 0;
			x = TypeUtil.calc_decimal_value(data, curbyte, i) ^ mask;
			
			if(x > Math.pow(10, intg0x+1))
			{
				mylog.error("over the maxvalue");
				return false;
			}
			curbyte += i;
			this.sb.append(x);
		}
		
		for(int i = 0; i < intg0; i++)
		{
			int x = TypeUtil.calc_decimal_value(data, curbyte, 4) ^ mask;
			if(x > Math.pow(10, MysqlDecimal.DEC_SIZE + 1))
			{
				mylog.error("over the maxvalue");
				return false;
			}
			curbyte += 4;
			this.sb.append(x);
		}
		this.sb.append('.');
		
		for(int i = 0; i < frac0; i++)
		{
			int x = TypeUtil.calc_decimal_value(data, curbyte, 4) ^ mask;
			if(x > Math.pow(10, MysqlDecimal.DEC_SIZE + 1))
			{
				mylog.error("over the maxvalue");
				return false;
			}
			curbyte += 4;
			this.sb.append(x);
		}
		
		if(frac0x > 0)
		{
			int i = MysqlDecimal.dig2bytes[frac0x];
			int x = TypeUtil.calc_decimal_value(data, curbyte, i) ^ mask;
			if(x > Math.pow(10, frac0x+1))
			{
				mylog.error("over the maxvalue");
				return false;
			}
			curbyte += i;
			this.sb.append(x);
		}
		
		return true;
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return sb.toString();
	}
	
	
	
	

}
